package com.xltt.vehicleControl.revice;

import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.text.TextUtils;
import android.widget.Toast;

import com.alibaba.sdk.android.push.MessageReceiver;
import com.alibaba.sdk.android.push.notification.CPushMessage;
import com.google.gson.Gson;
import com.xltt.vehicleControl.BuildConfig;
import com.xltt.vehicleControl.R;
import com.xltt.vehicleControl.activity.LauncherActivity;
import com.xltt.vehicleControl.activity.LoginActivity;
import com.xltt.vehicleControl.activity.PowerSettingsActivity;
import com.xltt.vehicleControl.base.MyApplication;
import com.xltt.vehicleControl.bean.ControlPushEvent;
import com.xltt.vehicleControl.bean.RemoteControlRequest;
import com.xltt.vehicleControl.bean.RemoteControlResponse;
import com.xltt.vehicleControl.bean.ReposFactory;
import com.xltt.vehicleControl.bean.ServiceResult;
import com.xltt.vehicleControl.bean.UserResponse;
import com.xltt.vehicleControl.contants.Constants;
import com.xltt.vehicleControl.util.ActivityManager;
import com.xltt.vehicleControl.util.KeyBreathableUtil;
import com.xltt.vehicleControl.util.Logger;
import com.alibaba.fastjson.JSON;
import com.xltt.vehicleControl.bean.UserResponse;
import com.xltt.vehicleControl.util.SharedPreferencesUtils;
import com.xltt.vehicleControl.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.Date;
import java.util.Map;


public class AliPushMessageReceiver extends MessageReceiver {

    public static final int REFRESH_UI = 8;//发送车控指令成功，刷新UI
    public static final int REFRESH_DATA = 15;//调用云端接口刷新车状态

    @Override
    protected void onNotification(Context context, String s, String s1, Map<String, String> map) {
        Logger.d("MyApplication onNotification = " + map.toString());
    }

    @Override
    protected void onMessage(Context context, CPushMessage cPushMessage) {
        if (cPushMessage.getContent() != null) {
            try {
                processCustomMessage(context,cPushMessage.getContent());
            } catch (Exception e) {
                Logger.d("pushError = " + e.getLocalizedMessage());
            }
        }
    }

    @Override
    protected void onNotificationOpened(Context context, String s, String s1, String s2) {
        Logger.d("MyApplication onNotificationOpened = ");
    }

    private void processCustomMessage(final Context context, String str){
        try {
            Logger.d("MyApplication 阿里推送原始数据 = " + str);
            RemoteControlResponse remoteControlResponse = JSON.parseObject(str,
                    RemoteControlResponse.class);
            Logger.d("MyApplication 阿里推送对象解析数据 = " + remoteControlResponse.toString());
            //1.获取登录的userId
            UserResponse userResponse = ReposFactory.getInstance().getUserResponse();
            String userId = "";
            if(userResponse != null){
                userId = userResponse.getUserId();
            }
            ServiceResult serviceResult = null;
            if (!TextUtils.isEmpty(userId) && remoteControlResponse != null &&
                    (serviceResult = remoteControlResponse.getServiceResult()) != null){
                String content = remoteControlResponse.getContent();
                String serviceId = remoteControlResponse.getServiceId();
                long messageTimeStamp = remoteControlResponse.getMessageTimeStamp();
                int operationResult = serviceResult.getOperationResult();
                String topActivityName = ActivityManager.getInstance().getTopActivity().getClass().getName();
                String loginActivityName = LoginActivity.class.getName();
                //2.远程诊断车辆结果（目前没有这个功能不会收到通知）
                if (RemoteControlRequest.SERVICE_ID_DIA.equals(serviceId)){
                    Logger.d("MyApplication SERVICE_ID_DIA");
                    return;
                }
                //3.判断是否异地登录
                if(!topActivityName.equals(loginActivityName) && operationResult == ServiceResult.RESULT_OTHER_DEVICE){
                    Logger.d("MyApplication Aaccount error login");
                    saveDataToDB(context,serviceId,context.getString(R.string.other_user_push_msg),messageTimeStamp);
                    EventBus.getDefault().post(new ControlPushEvent(ServiceResult.RESULT_OTHER_DEVICE));
                    return;
                }
                /*
                   4.所有车控命令执行成功，需要更新UI
                   0 、2、3、4、 代表车控指令发送成功
                   15 = 代表需要重更新获取接口数据，刷新UI
                   60 = 代表车辆警告、例如车子未关门
                   50 = 防盗消息
                 */
                if(operationResult == 60
                        || operationResult == 50
                        || operationResult == 0
                        || operationResult == 2
                        || operationResult == 3
                        || operationResult == 4
                        || operationResult == 15){
                    //过滤空内容并且不是刷新数据命令
                    if(!TextUtils.isEmpty(content)){
                        saveDataToDB(context,serviceId,content,messageTimeStamp);
                    }
                    if(operationResult == 60 || operationResult == 50){
                        ToastUtil.show(context,content);
                        return;
                    }
                    if(operationResult == 0 || operationResult == 2 || operationResult == 3 || operationResult == 4){
                        EventBus.getDefault().post(new ControlPushEvent(REFRESH_UI));
                        return;
                    }
                    Logger.d("operationResult = " + operationResult);
                    if(operationResult == 15){
                        EventBus.getDefault().post(new ControlPushEvent(REFRESH_DATA));
                        return;
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }


    private void startReLogin(Context context) {
        context.startActivity(new Intent(context,LoginActivity.class));
        ActivityManager.getInstance().finishAllActivities(LoginActivity.class);
    }


    @Override
    protected void onNotificationClickedWithNoAction(Context context, String s, String s1, String s2) {

    }

    @Override
    protected void onNotificationRemoved(Context context, String s) {

    }

    @Override
    protected void onNotificationReceivedInApp(Context context, String s, String s1, Map<String, String> map, int i, String s2, String s3) {

    }


    /**
     * 获取车控指令
     * @param context
     * @param serviceId
     * @return
     */
    private String getServiceCmd(Context context,String serviceId){
        //RTU
        if(serviceId.equalsIgnoreCase(RemoteControlRequest.SERVICE_ID_RHL)){
            serviceId = context.getString(R.string.service_id_rhl);
        }else if(serviceId.equalsIgnoreCase(RemoteControlRequest.SERVICE_ID_RCE)){
            serviceId = context.getString(R.string.service_id_rce);
        }else if(serviceId.equalsIgnoreCase(RemoteControlRequest.SERVICE_ID_RDL)){
            serviceId = context.getString(R.string.service_id_rdl);
        }else if(serviceId.equalsIgnoreCase(RemoteControlRequest.SERVICE_ID_RDU)){
            serviceId = context.getString(R.string.service_id_rdu);
        }else if(serviceId.equalsIgnoreCase(RemoteControlRequest.SERVICE_ID_RES)){
            serviceId = context.getString(R.string.service_id_res);
        }else if(serviceId.equalsIgnoreCase(RemoteControlRequest.SERVICE_ID_RWS)){
            serviceId = context.getString(R.string.service_id_rws);
        }else if(serviceId.equalsIgnoreCase(RemoteControlRequest.SERVICE_ID_RTU)){
            serviceId = context.getString(R.string.service_id_rws);
        }else{
            serviceId = context.getString(R.string.unknown);
        }
        return serviceId;

    }

    /**
     * 保存数据到数据库给桌面显示通知
     * @param context
     * @param cmd
     * @param content
     * @param time
     */
    private void saveDataToDB(Context context,String cmd,String content,long time){
        ControlPushEvent pushEvent = new ControlPushEvent();
        pushEvent.setCmd(cmd);
        pushEvent.setOperationTime(time);
        pushEvent.setContent(content);
        pushEvent.setServiceId(context.getPackageName());
        String data = new Gson().toJson(pushEvent);
        Logger.d("MyApplication 保存通知车控数据 = " + data);
        if(Constants.DEBUG){
            SharedPreferencesUtils.setParam(context,Constants.VEHICLE_CMD_LIST,data);
        }else{
            Settings.Global.putString(context.getContentResolver(), Constants.VEHICLE_CMD_LIST, data);
        }
    }

}


